
'''west "relase" command'''
import os
import colorama
from textwrap import dedent            # just for nicer code indentation
from west.commands import WestCommand
from west.configuration import config
from west import log
import subprocess

RELASE_SHELL = "shell/relase.sh"
class Relase(WestCommand):
    def __init__(self):
        super(Relase, self).__init__(
            'relase',
            # Keep this in sync with the string in west-commands.yml.
            'Compile and download the program to the board',
            dedent("Compile and download bin file the program to the board."),
            accepts_unknown_args=True)
        
    def do_add_parser(self, parser_adder):
        parser = parser_adder.add_parser(self.name,
                                        help=self.help,
                                        description=self.description)
        # 需要下载和编译的文件
        parser.add_argument('-n', '--filename',default=None, help='bin filename')
        # 需要下载的文件地址
        parser.add_argument('-a','--address',default=None, help='bin address')
        # 是否需要下载到板子上
        parser.add_argument('-f', '--flash',default=False, action='store_true',help='bin filename')
        # 是否需要清理工程
        parser.add_argument('-c', '--clean',default=False, action='store_true',help='clean project')
        # 验签需要用到的key文件
        parser.add_argument('-k', '--keys',default=None, help='key file')
        # mcuboot的二进制文件需要偏移大小，以k为单位
        parser.add_argument('-o', '--office',default=None, help='mcuboot bin office')
        return parser
    
    def do_run(self, args, unknown_args):
        path = os.path.dirname(os.path.abspath(__file__))
        #log.inf(path)
        relase_file = os.path.join(path,RELASE_SHELL)
        if not os.path.exists(relase_file):
                raise RuntimeError('relase.sh file is not')
        cmd=["sh",relase_file]
        if args.filename is not None:
            cmd.extend(['-n',args.filename])
        if args.address is not None:
            cmd.extend(['-a',args.address])
        if args.flash == True:
            cmd.extend(['-f'])
        if args.clean == True:
            cmd.extend(['-c'])
        if args.keys is not None:
            cmd.extend(['-k',args.keys])
        if args.office is not None:
            cmd.extend(['-o',args.office])
        
        # log.inf("cmd:",cmd)
        relase_excute = subprocess.Popen(cmd,stdout=subprocess.PIPE,bufsize=200,cwd=os.path.dirname(relase_file),universal_newlines=True)
        for msg in iter(relase_excute.stdout.readline,''):
                log.msg(msg,color=colorama.Fore.GREEN)